<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;


/**
 * 会员接口
 */
class Coach extends Api
{
    protected $noNeedLogin = '';
    protected $noNeedRight = '*';

    /*
     * 课程提醒
     * */
    public function remind()
    {
        $uid = $this->auth->id;
        $list = Db::table('keep_term')
            ->alias('t')
            ->join('keep_course c','c.id = t.course_id')
            ->join('keep_time m','t.time_id = m.id')
            ->where('t.user_id',$uid)
            ->order('t.stime')
            ->where('t.deletetime',null)
            ->where('t.type', '1')
            ->where('t.status', '0')
            ->field('t.id as term_id,  t.name,  t.stime as date,  c.id as course_id,  c.name as courseName, c.image, c.type, m.stime ')
            ->select()
            ->toArray();

        $list1 = Db::table('keep_term')
            ->alias('t')
            ->join('keep_course c','c.id = t.course_id')
            ->join('keep_time m','t.time_id = m.id')
            ->where('t.user_id',$uid)
            ->order('t.stime')
            ->where('t.deletetime',null)
            ->where('t.type', '0')
            ->where('t.status', '0')
            ->field('t.id as term_id,  t.name,  t.stime as date,  c.id as course_id,  c.name as courseName, c.image, c.type, m.stime ')
            ->select()
            ->toArray();
        $lista = array_merge($list,$list1);
        foreach ($lista as &$v) {
            $v['num']  = DB::name('user_course')->where('term_id',$v['term_id'])->where('status',0)->count();
            $v['image'] = cdnurl($v['image'], true);
        }
        $this->success('课程提醒', $lista);
    }
    
    /*
     * 我的课程
     * */
    public function courseList()
    {
        $uid = $this->auth->id;
        $list = Db::table('keep_term')
            ->alias('t')
            ->join('keep_course c','c.id = t.course_id')
            ->join('keep_venue v','v.id = t.venue_id')
            ->where('t.user_id',$uid)
            ->order('t.stime')
            ->where('t.type', '<>','2')
            ->where('t.status', '0')
            ->field('t.id as term_id, c.id as course_id,  c.name as courseName, c.image, c.type, v.name as venueName, v.address')
            ->select()
            ->toArray();
        $list1 = Db::table('keep_term')
            ->alias('t')
            ->join('keep_course c','c.id = t.course_id')
            ->join('keep_venue v','v.id = t.venue_id')
            ->where('t.user_id',$uid)
            ->order('t.stime')
            ->where('t.type', '2')
            ->where('t.status', '0')
            ->field('t.id as term_id, c.id as course_id,  c.name as courseName, c.image, c.type, v.name as venueName, v.address')
            ->select()
            ->toArray();
        $lista = array_merge($list,$list1);
        if ($lista) {
            foreach ($lista as &$v) {
                $v['num']  = DB::name('user_course')->where('term_id',$v['term_id'])->where('status',0)->count();
                $v['image'] = cdnurl($v['image'], true);
            }
        }

        $this->success('课程列表', $lista);
    }

    /*
     * 课程计划
     * */
    public function coursePlan()
    {
        $this->checkParam( ['course_id', 'term_id']);
        $term_id = $this->request->request('term_id');

        $course_id = $this->request->request('course_id');
        $course = DB::name('course')->where('id', $course_id)->find();
        $term = DB::name('term')->where('id', $term_id)->find();

        if (!$course || !$term) {
            $this->error('暂无详情');
        }
        $list = DB::name( 'course_plan' )
                ->where( 'course_id', $course_id )
                ->where( 'status', '0' )
                ->field( 'id as plan_id, name, image' )
                ->select()
                ->toArray();
        if (!$list) {
            $this->success('课程计划', $list);
        }

        foreach ($list as &$v ) {
                $v['image'] = cdnurl($v['image'], true);

            //去查询课程计划开课状态，null就是没有开课待开始
            $record = DB::name( 'user_course_plan' )
                ->where( 'course_plan_id', $v['plan_id'])
                ->where( 'term_id', $term_id)
                ->find();
            if ($record) {
                $v['type']  = $record['type'];
            } else {
                $v['type'] = null;
            }

        }
        $this->success('课程计划', $list);




    }
    
    /*
     * 课程详情
     * */
    public function courseInfo()
    {
        $this->checkParam('term_id');
        $term_id = $this->request->request('term_id');
        $term = DB::name('term')->where('id', $term_id)->find();
        $time = DB::name('time')->where('id', $term['time_id'])->find();
        if (!$term) {
            $this->error('暂无详情');
        }
        $info = Db::table('keep_course')
            ->alias('c')
            ->join('keep_term t','c.id = t.course_id','left')
            ->join('keep_venue v','v.id = t.venue_id','left')
            ->where('c.id',$term['course_id'])
            ->field('t.stime, v.name as venueName, v.address,c.id as course_id, c.name as courseName, c.image,c.describe')
            ->find();
        $info['image'] = cdnurl($info['image'], true);
        $info['sDate'] = $term['stime'];
        $info['eDate'] = $term['etime'];
        $info['sTime'] = $time['stime'];
        $info['eTime'] = $time['etime'];
        $info['userList'] = Db::table('keep_user_course')
            ->alias('c')
            ->join('keep_user u','u.id = c.user_id','left')
            ->where('c.term_id',$term_id)
            ->where('c.status','0')
            ->field('u.avatar, u.username, u.school')
            ->select()
            ->toArray();
        $info['num'] = count($info['userList']);
       /* if ($info['userList']) {
            foreach ( $info['userList'] as &$v ) {
                if ($v['avatar']) {
                    $v['avatar'] = cdnurl($v['avatar'], true);
                }
            }
        }*/

        $this->success('课程详情', $info);
    }
    
    /*
     * 课程小节
     * */
    public function courseNode()
    {
        $this->checkParam( ['term_id','plan_id']);
        $term_id = $this->request->request('term_id');
        $plan_id = $this->request->request('plan_id');
        $plan = DB::name('course_plan')->where('id', $plan_id)->find();
        $term = DB::name('term')->where('id', $term_id)->find();
        if (!$plan || !$term) {
            $this->error('暂无详情');
        }

        $list = DB::name( 'course_node' )
            ->where( 'course_plan_id', $plan_id )
            ->where( 'status', '0' )
            ->field( 'id as node_id, name' )
            ->select()
            ->toArray();
        if ($list) {
            foreach ( $list as &$v ) {
                //去查询小节开课状态，null就是没有开课待开始
                $record = DB::name( 'user_course_node' )
                    ->where( 'course_node_id', $v['node_id'])
                    ->where( 'term_id', $term_id)
                    ->find();
                if ($record) {
                    $v['type']  = $record['type'];
                } else {
                    $v['type'] = null;
                }
            }
        }

        $this->success('课程小节', $list);
    }
    
    /*
     * 课程打卡
     * */
    public function nodeSign()
    {
        $this->checkParam( ['term_id','id']);
        $term_id = $this->request->request('term_id');
        $node_id = $this->request->request('id');
        $data = file_get_contents("php://input");
        $node = DB::name('course_node')->where('id', $node_id)->find();
        $term = DB::name('term')->where('id', $term_id)->find();
        if (!$node || !$term) {
            $this->error('暂无详情');
        }
        if ($data) {

            $data = json_decode($data,'true');
            Db::startTrans();
            foreach ($data as $val) {
                //判断用户的课程状态
                $userCourse = DB::name('user_course')
                    ->where('user_id', $val['user_id'])
                    ->where('course_id', $node['course_id'])
                    ->where('term_id', $term_id)
                    ->where('status', '0')
                    ->find();


                if (!$userCourse) {
                    Db::rollback();
                    $this->error('用户暂无该课程，请检查');
                }
                //修改用户课程状态
                if ($userCourse['type'] != 2) {
                    DB::name('user_course')->where('id', $userCourse['id'])->update(['type'=>2]);
                }
                //判断用户开课时间，没有则添加，有就不更改
                if (!$userCourse['stime']) {
                    DB::name('user_course')->where('id', $userCourse['id'])->update(['stime'=>time()]);
                }


                //判断课程计划是否存在，没有则插入一条进行中的课程计划
                $userPlan = DB::name('user_course_plan')
                    ->where('user_id', $val['user_id'])
                    ->where('course_plan_id', $node['course_plan_id'])
                    ->where('term_id', $term_id)
                    ->find();
                if (!$userPlan) {
                    $userPlan = [
                        'venue_id' => $node['venue_id'],
                        'term_id' => $term_id,
                        'course_id' => $node['course_id'],
                        'user_id' => $val['user_id'],
                        'course_plan_id' => $node['course_plan_id'],
                        'type' => 0,
                        'stime' => time()
                    ];
                    DB::name('user_course_plan')->insert($userPlan);
                }



                //查询打卡记录，没有则插入一条正在进行的打卡记录，有则修改打卡状态
                $userNode = DB::name('user_course_node')
                        ->where('user_id', $val['user_id'])
                        ->where('course_node_id', $node_id)
                        ->where('term_id', $term_id)
                        ->find();


                if ($userNode) {
                    //评分以后就不允许修改打卡了
                    if ($userNode['grade']) {
                        Db::rollback();
                        $this->error('该课程已经评分，不支持打卡了！');
                    }
                    DB::name('user_course_node')->where('id', $userNode['id'])->update(['absent'=>$val['absent']]);

                } else {
                    //插入一条用户进行中的小节记录
                    $userNode = [
                        'venue_id' => $node['venue_id'],
                        'term_id' => $term_id,
                        'course_id' => $node['course_id'],
                        'user_id' => $val['user_id'],
                        'course_plan_id' => $node['course_plan_id'],
                        'course_node_id' => $node_id,
                        'absent' => $val['absent'],
                        'type' => 0,
                        'stime' => time()
                    ];
                    DB::name('user_course_node')->insert($userNode);
                }
            }
            //修改学期为进行中的状态
            if ($term['type'] != 1) {
                DB::name('term')->where('id', $term_id)->update(['type'=>1]);
            }
            Db::commit();
            $this->success('打卡成功');
        } else {
            //查看或者编辑打卡记录
            $list = Db::table('keep_user_course')
                ->alias('c')
                ->join('keep_user u','u.id = c.user_id','left')
                ->where('c.term_id',$term_id)
                ->where('c.status','0')
                ->field('u.id as user_id, u.avatar, u.username')
                ->select()
                ->toArray();

            foreach ($list as &$v) {
                $v['absent'] = DB::name('user_course_node')
                            ->where('term_id', $term_id)
                            ->where('course_node_id', $node_id)
                            ->where('user_id', $v['user_id'])
                            ->value('absent');
            }
            $this->success('课程打卡', $list);
        }
    }

    /*
     * 课程评分
     * */
    public function grade()
    {
        $this->checkParam( ['term_id','id']);
        $term_id = $this->request->request('term_id');
        $node_id = $this->request->request('id');
        $data = file_get_contents("php://input");
        $node = DB::name('course_node')->where('id', $node_id)->find();
        $term = DB::name('term')->where('id', $term_id)->find();
        //dump($term);die;
        if (!$node || !$term || $node['course_id'] != $term['course_id']) {
            $this->error('暂无详情');
        }


        $list = Db::table('keep_user_course')
            ->alias('c')
            ->join('keep_user u','u.id = c.user_id','left')
            ->where('c.term_id',$term_id)
            ->where('c.status','0')
            ->field('u.id as user_id, u.avatar, u.username')
            ->select()
            ->toArray();
        //查看评分记录
        foreach ($list as &$v) {
            $v['grade'] = DB::name('user_course_node')
                ->where('term_id', $term_id)
                ->where('course_node_id', $node_id)
                ->where('user_id', $v['user_id'])
                ->value('grade');
        }

        if ($data) {

           /* $data = [
                [
                    'user_id' => 1,
                    'grade' => 1
                ],
                [
                    'user_id' => 7,
                    'grade' => 0
                ]
            ];*/
            $data = json_decode($data,'true');

            //判断是否评价了所有的学员
            $postUser = [];
            $termUser = [];
            foreach ($data as $value) {

                //判断是否有评分
                if (isset($value['grade'])) {
                    $postUser[] = $value['user_id'];
                }
            }

            foreach ($list as $item) {
                $termUser[] = $item['user_id'];
            }

            //比较提交评分的学员跟学期学员是否一致
            if ($termUser != $postUser) {
                $this->error('请评价所有的学员，还有学员未被评分！');
            }
            Db::startTrans();
            foreach ($data as $val) {
                //判断用户是否有这个课程
                $userCourse = DB::name('user_course')
                    ->where('user_id', $val['user_id'])
                    ->where('course_id', $node['course_id'])
                    ->where('term_id', $term_id)
                    ->find();
                if (!$userCourse) {
                    Db::rollback();
                    $this->error('用户暂无该课程，请检查');
                }

                //判断学员的打卡状态并且修改评分以及小节课程状态
                $userNode = DB::name('user_course_node')
                    ->where('user_id', $val['user_id'])
                    ->where('course_node_id', $node_id)
                    ->where('term_id', $term_id)
                    ->find();
                //判断用户小节课程是否有记录，没记录则是没打卡，
                //如果该学员没打卡记录就在不支持评分
                if (!$userNode || !isset($userNode['absent'])) {
                    Db::rollback();
                    $this->error('该课程有学员没完成打卡，请先打卡！');
                }
                //评分以后就不允许修改评分了
                if ($userNode['grade']) {
                    Db::rollback();
                    $this->error('该课程已经评分，不支持二次评分！');
                }

                //添加课程评分
                if ($userNode['absent'] == 1) {
                    //如果该课程缺勤则判断不及格
                    $grade = 3;
                } else {
                    $grade = $val['grade'];
                }

                //修改小节课程结束时间以及课程状态
                $ret =DB::name('user_course_node')->where('id', $userNode['id'])->update(['grade'=> $grade, 'type' => 1, 'etime' =>time()]);
            }

            //判断是否是最后的课程小节，是则修改课程计划的状态
            $endNode = Db::table('keep_course_node')
                    ->where('course_plan_id', $node['course_plan_id'])
                    ->where('status', 0)
                    ->where('deletetime',null)
                    ->order('weigh', 'desc')
                    ->order('id', 'desc')
                    ->value('id');

            if ($endNode == $node_id) {

                //修改整个课程计划状态
                DB::name('user_course_plan')
                    ->where('course_plan_id', $node['course_plan_id'])
                    ->where('term_id', $term_id)
                    ->where('course_id', $node['course_id'])
                    ->update([ 'type' => 1, 'etime' => time() ]);
                //判断是否是最后的课程计划，是则修改课程课程的状态
                $endPlan = Db::table('keep_course_plan')
                    ->where('course_id', $node['course_id'])
                    ->where('status', 0)
                    ->where('deletetime',null)
                    ->order('weigh', 'desc')
                    ->order('id', 'desc')
                    ->value('id');

                if ($endPlan == $node['course_plan_id']) {
                    //修改整个课程状态
                    DB::name('user_course')
                        ->where('term_id', $term_id)
                        ->where('course_id', $node['course_id'])
                        ->update([ 'type' => 3, 'etime' => time() ]);
                    //修改学期状态
                    DB::name('term')
                        ->where('id', $term_id)
                        ->update([ 'type' => 2 ]);
                }
            }

            Db::commit();
            $this->success('评分成功');
        }
        $this->success('课程评分', $list);
    }
}
